package com.ohos.connect.devicecloud.iot.util;

import cn.hutool.core.util.HexUtil;

import java.security.SecureRandom;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.spec.KeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
public class PBKDF2Util {
    private static final int SALT_LEN = 16;
    private static final int PASS_LEN = 32;
    private static final int KEY_LEN = 32;
    private static final int ITERATION = 1;
    public static void main(String[] args) {
       // saltValue 为sn1（hex变为binary后为8 bytes）和 sn2（hex变为binary后为8 bytes）的拼装，saltValue长度为16 bytes
        byte[] saltValue = new byte[SALT_LEN];
        SecureRandom random = new SecureRandom();
        random.nextBytes(saltValue);
        String saltHexStr = HexUtil.encodeHexStr(saltValue);
        System.out.println("sn1:"+ saltHexStr.substring(0,16));
        System.out.println("sn2:"+ saltHexStr.substring(16));
        System.out.println(saltHexStr);
        saltHexStr = "dc582466952bfed6191289c02f249422";
        String password = "testtesttesttest";

        try {
            byte[] key = pbkdf2(password, saltValue, ITERATION, KEY_LEN);
            System.out.println("PKCS#5:");
            System.out.println(HexUtil.encodeHexStr(key));

        //    System.out.println(pbkdf2(password, saltHexStr, ITERATION, KEY_LEN));
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
        }

    }
    public static String pbkdf2(String password, String saltHexStr, int iteration, int keyLength) throws InvalidKeySpecException, NoSuchAlgorithmException {
        byte[] key = pbkdf2(password, HexUtil.decodeHex(saltHexStr), ITERATION, KEY_LEN);
        return HexUtil.encodeHexStr(key);
    }


    /**
     *
     * @param password
     * @param salt salt 为sn1（hex变为binary后为8 bytes）和 sn2（hex变为binary后为8 bytes）的拼装，salt长度为16 bytes
     * @param iteration
     * @param keyLength
     * @return
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     */
    public static byte[] pbkdf2(String password, byte[] salt, int iteration, int keyLength) throws InvalidKeySpecException, NoSuchAlgorithmException {
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, ITERATION, KEY_LEN * 8);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        return factory.generateSecret(spec).getEncoded();
    }
}
